package cn.tsvtc.shop.service.impl;/**
 * @Author Athena
 * @Date 2020/11/2 21:26
 * @Version 1.0
 * @Description no description
 */

import cn.tsvtc.shop.entity.ResultMessage;
import cn.tsvtc.shop.mapper.SearchMapper;
import cn.tsvtc.shop.pojo.SearchProduct;
import cn.tsvtc.shop.service.SearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.solr.client.solrj.SolrClient;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrRequest;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.client.solrj.response.UpdateResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import org.apache.solr.common.SolrInputDocument;
import org.apache.solr.common.params.SolrParams;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;

/**
 * @author: Athena
 * @date: 2020/11/2 21:26
 * @description:
 */
@Service
@Slf4j
public class SearchServiceImpl implements SearchService {

    private SearchMapper searchMapper;

    private SolrClient solrClient;

    @Autowired
    public SearchServiceImpl(SolrClient solrClient,SearchMapper searchMapper){
        this.solrClient=solrClient;
        this.searchMapper=searchMapper;
    }


    /**
     * 存入solr
     *
     * @return
     */
    @Override
    public ResultMessage init() {


        try {
            Collection<SolrInputDocument> docs=new ArrayList<>();
            List<SearchProduct> searchProducts = searchMapper.findAll();
            log.error("init获取到数据库条数==>"+searchProducts.size());
            for (SearchProduct product : searchProducts) {
                SolrInputDocument solrInputDocument=new SolrInputDocument();
                solrInputDocument.addField("id",product.getId().toString());
                solrInputDocument.addField("product_pname",product.getPname());
                solrInputDocument.addField("product_price",product.getPrice().floatValue());
                solrInputDocument.addField("product_pimage",product.getPimage());
                solrInputDocument.addField("product_pdesc",product.getPdesc());
                docs.add(solrInputDocument);
            }
            log.error("init插入solr条数==>"+docs.size());
            solrClient.add(docs);
            solrClient.commit();
            return new ResultMessage();
        } catch (SolrServerException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return new ResultMessage(false,"failed","失败");
    }

    /**
     * 搜索
     *
     * @return
     */
    @Override
    public List<SearchProduct> search(String keyword) {
        List<SearchProduct> searchProducts=new ArrayList<>();
        SolrQuery solrQuery=new SolrQuery();
        solrQuery.setQuery(keyword);
        //df=default field
        solrQuery.set("df","product_keyword");
        solrQuery.setHighlight(true);
        solrQuery.setHighlightSimplePre("<span style='color:red;'>");
        solrQuery.setHighlightSimplePost("</span>");
        solrQuery.addHighlightField("product_pname");
        try {
            QueryResponse queryResponse = solrClient.query(solrQuery, SolrRequest.METHOD.GET);
            //总的结果
            SolrDocumentList results = queryResponse.getResults();
            //带高亮的结果，只有id和高亮域
            Map<String, Map<String, List<String>>> highlighting = queryResponse.getHighlighting();
            for (SolrDocument result : results) {
                //遍历所有结果
                String id = (String) result.getFieldValue("id");
                String product_pname = (String) result.getFieldValue("product_pname");
                Float product_price = (Float) result.getFieldValue("product_price");
                String product_pimage = (String) result.getFieldValue("product_pimage");
                String product_pdesc = (String) result.getFieldValue("product_pdesc");

                //去搜索高亮的有没有一致的 product_pname
                Map<String, List<String>> listMap = highlighting.get(id);
                if(listMap.size()>0){
                    List<String> strings = listMap.get("product_pname");
                    String str = strings.get(0);
                    //将searchProduct的pname修改
                    product_pname=str;
                }


                SearchProduct searchProduct=new SearchProduct();
                searchProduct.setId(Long.parseLong(id));
                searchProduct.setPname(product_pname);
                searchProduct.setPrice(product_price.longValue());
                searchProduct.setPimage(product_pimage);
                searchProduct.setPdesc(product_pdesc);
                searchProducts.add(searchProduct);
            }
            return searchProducts;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return searchProducts;
    }
}
